package cn.getech.data.development.controller.datasyn;

import cn.getech.data.development.constant.*;
import cn.getech.data.development.entity.DataSyncInfo;
import cn.getech.data.development.model.dto.*;
import cn.getech.data.development.service.DataSyncInfoService;
import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.data.intelligence.common.utils.R;
import cn.getech.system.center.annotation.SysLog;
import cn.getech.system.center.constant.OperationModulesEnum;
import cn.getech.system.center.constant.OperationTypeEnum;
import cn.getech.system.center.constant.module.ModuleEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author luoxi
 * @create 2020/11/16 14:49
 */
@Slf4j
@Api(tags = "整库同步信息")
@RestController
@RequestMapping(value = "/bdq/sync")
public class DataSyncInfoController {
    Logger logger = LoggerFactory.getLogger(DataSyncInfoController.class);

    @Autowired
    private DataSyncInfoService dataSyncInfoService;


    @PostMapping(value = "/add")
    @SysLog(value = "新建整库同步任务", type = OperationTypeEnum.ADDCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "新建整库同步任务")
    public R add(@RequestBody DataSyncInfoAddDTO dataSyncInfoAddDTO) {
        logger.info("/add参数接收:{}", JSON.toJSONString(dataSyncInfoAddDTO));
        dataSyncInfoService.add(dataSyncInfoAddDTO);
        return R.ok();
    }

    @PostMapping(value = "/listPage")
    //@SysLog(value = "整库同步任务多条件分页查询", type = OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "整库同步任务多条件分页查询")
    public R listPage(@RequestBody DataSyncQueryDTO dataSyncQueryDTO) {
        logger.info("/listPage参数接收:{}", JSON.toJSONString(dataSyncQueryDTO));
        IPage<DataSyncInfo> page = dataSyncInfoService.listPage(dataSyncQueryDTO);
        return R.okWithPage(page);
    }


    @GetMapping(value = "/get/{id}")
    @SysLog(value = "整库同步任务详情查询", type = OperationTypeEnum.GETCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "整库同步任务详情查询")
    public R getById(@PathVariable(value = "id") Integer id) {
        logger.info("/get参数接收:{}", JSON.toJSONString(id));
        Optional.ofNullable(id).orElseThrow(() -> new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR.getMessage()));
        DataSyncReturnDTO dataSyncReturnDTO = dataSyncInfoService.get(id);
        return R.okWithData(dataSyncReturnDTO);
    }

    @PostMapping(value = "/del")
    @SysLog(value = "整库同步任务删除", type = OperationTypeEnum.DELETECODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "整库同步任务删除")
    public R del(@RequestBody Map<String,List<Integer>> hashMap) {
        logger.info("/del参数接收:{}", JSON.toJSONString(hashMap));
        dataSyncInfoService.del(hashMap.get("ids"));
        return R.ok();
    }


    @PostMapping(value = "/edit")
    @SysLog(value = "整库同步任务更新", type = OperationTypeEnum.UPDATECODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "整库同步任务更新")
    public R del(@RequestBody DataSyncInfoAddDTO dataSyncInfoAddDTO) {
        logger.info("/edit参数接收:{}", JSON.toJSONString(dataSyncInfoAddDTO));
        dataSyncInfoService.edit(dataSyncInfoAddDTO);
        return R.ok();
    }

    @GetMapping(value = "/getByDataSource/{dataSourceType}")
    //@SysLog(value = "根据数据来源查询数据源信息", type = OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "根据数据来源查询数据源信息")
    public R getByDataSource(@PathVariable(value = "dataSourceType") Integer dataSourceType) {
        logger.info("/getByDataSource参数接收:{}", JSON.toJSONString(dataSourceType));
        List<DataSourceLevelDTO> dataSourceLevelDTOList = dataSyncInfoService.getByDataSource(dataSourceType);
        return R.okWithData(dataSourceLevelDTOList);
    }

    @PostMapping(value = "/getByDataBase")
    //@SysLog(value = "根据数据库查询来源表信息", type = OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    @ApiOperation(value = "根据数据库查询来源表信息")
    public R getByDataBase(@RequestBody DataBaseDTO dataBaseDTO) {
        logger.info("/getByDataBase参数接收:{}", JSON.toJSONString(dataBaseDTO));
        Optional.ofNullable(dataBaseDTO).orElseThrow(() -> new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR.getMessage()));
        PageUtils<DataSyncMetaDataReturnDTO> page = dataSyncInfoService.getByDataBase(dataBaseDTO);
        return R.okWithData(page);
    }

    @GetMapping(value = "/getTaskStatus")
    @ApiOperation(value = "任务状态筛选列表")
    //@SysLog(value = "任务状态筛选列表", type = OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    public R getTaskStatus() {
        List<JSONObject> list = new ArrayList<>();
        for (DataSyncTaskEnum value : DataSyncTaskEnum.values()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(String.valueOf(value.getCode()), value.getMessage());
            list.add(jsonObject);
        }
        return R.okWithData(list);
    }


    @GetMapping(value = "/tableOrData/{id}/{syncQueue}")
    @ApiOperation(value = "同步表结构或者数据")
    @SysLog(value = "同步表结构或者数据", type = OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    public R syncDataOrTable(@PathVariable(value = "id") Integer id,
                             @PathVariable(value = "syncQueue") String syncQueue) {
        if (id == null) {
            return R.error("id不能为空");
        }
        if (StringUtils.isEmpty(syncQueue)) {
            return R.error("任务指定队列不能为空");
        }
        return dataSyncInfoService.syncDataOrTable(id, syncQueue);
    }

    @GetMapping(value = "/getLogInfo/{id}")
    @ApiOperation(value = "得到日志信息")
    @SysLog(value = "得到整库同步的日志信息", type = OperationTypeEnum.GETCODE, modulesType = OperationModulesEnum.TABLEMODELCODE,platformModuleType = ModuleEnum.DATA_CONVERGE_MODULE_CODE)
    public R getLogInfo(@PathVariable(value = "id") Integer id) {
        if (Objects.isNull(id)) {
            throw new RRException("param error!");
        }
        return R.okWithData(dataSyncInfoService.getLogInfo(id));
    }

    @GetMapping(value = "/getHiveList")
    @ApiOperation(value = "查询hive库列表")
    public R getHiveList() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        for (DataSyncDatabaseEnum value : DataSyncDatabaseEnum.values()) {
            jsonObject = new JSONObject();
            jsonObject.put("id", value.getId());
            jsonObject.put("name", value.getName());
            jsonObject.put("isDefault", value.isDefault());
            jsonArray.add(jsonObject);
        }
        return R.okWithData(jsonArray);
    }

    @GetMapping(value = "/getWriteRuleList")
    @ApiOperation(value = "查询写入规则列表")
    public R getWriteRuleList() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        for (DataSyncWriteRuleEnum value : DataSyncWriteRuleEnum.values()) {
            jsonObject = new JSONObject();
            jsonObject.put("id", value.getId());
            jsonObject.put("name", value.getName());
            jsonObject.put("isDefault", value.isDefault());
            jsonArray.add(jsonObject);
        }
        return R.okWithData(jsonArray);
    }

    @GetMapping(value = "/getStorageFormatList")
    @ApiOperation(value = "查询存储格式列表")
    public R getStorageFormatList() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        for (DataSyncStorageFormatEnum value : DataSyncStorageFormatEnum.values()) {
            jsonObject = new JSONObject();
            jsonObject.put("id", value.getId());
            jsonObject.put("name", value.getName());
            jsonObject.put("isDefault", value.isDefault());
            jsonArray.add(jsonObject);
        }
        return R.okWithData(jsonArray);
    }

    @GetMapping(value = "/getCreateUserList")
    @ApiOperation(value = "任务创建人下拉框")
    public R getCreateUserList() {
        Set<ApplyUserListDTO> createUserList=dataSyncInfoService.getCreateUserList();
        return R.okWithData(createUserList);
    }


    @PostMapping(value = "/getDataSourceByType")
    @ApiOperation(value = "通过数据来源获取数据源 去元数据列表那里回去数据源信息")
    public R getDataSourceByType(@RequestBody DataSyncDataSourceDTO dataSyncDataSourceDTO) {
        PageUtils pageUtils=dataSyncInfoService.getDataSourceByType(dataSyncDataSourceDTO);
        return R.okWithPage(pageUtils);
    }


}